<?php
namespace classlib\core\view;
class json extends view_abstract {
	private $smart = array();
	public function __construct($params=null) {
		$this->smart = array('code'=>0, 'success'=>true);
	}
	
	/**
	 * 变量赋值
	 * @param string $key
	 * @param mix    $val
	 * @return view_abstract
	 */
	public function assign($key, $val) {
		$this->smart[$key] = $val;
		return $this;
	}
	
	/**
	 * 变量赋值引用赋值
	 * @param string $key
	 * @param mix $val
	 * @return view_abstract
	 */
	public function assign_by_ref($key, &$val) {
		$this->smart[$key] = $val;
		return $this;
	}
	
	/**
	 * 错误码复制直接退出
	 * @param string $code
	 * @param string $msg
	 */
	public function assign_error($code, $msg) {
		$this->smart['code']    = $code;
		$this->smart['msg']     = $msg;
		$this->smart['success'] = false;
		$this->display();
		exit;
	}

	/**
	 * 已经分配的变量的获取 默认取所有
	 * @param string $key
	 * @return mix
	 */
	public function get_template_vars($key=false) {
		if($key) {
			$data = isset($this->smart[$key])? $this->smart[$key]:false;
			return $data;
		}
		return $this->smart;
	}
	
	/**
	 * 将要输出的资料获取
	 * @param string  $tpl
	 * @param boolean $iscache
	 * @return string
	 */
	public function fetch($tpl=false) {
		$str = json_encode($this->smart);
		return $str;
	}
	
	/**
	 * 重载Smarty输出的资料输出
	 * @param string  $tpl
	 * @param int     $caching 
	 * @param string  $cacheid  区别同一个页面不同展示模版
	 * @param int     $lifetime
	 * @see Smarty  $caching
	 */
	public function display($tpl=false, $caching=0, $cacheid=null, $lifetime=3600) {
		parent::display();
		echo $this->fetch();
	}
}